package com.pbase.data.http.interceptor;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by goldze on 2017/5/10.
 * 请求头拦截器
 */
public class HeadInterceptor implements Interceptor {
    /**
     * 在 @Headers 注解的第一位添加该请求头，将会替换拦截器中配置的请求头信息
     */
    public static final String REPLACE_HEADS = "replaceHeads";
    private Map<String, String> headers;

    public HeadInterceptor(Map<String, String> headers) {
        this.headers = headers;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder builder = chain.request()
                .newBuilder();
        Headers headers = chain.request().headers();
        if (headers.get(REPLACE_HEADS )!=null){//只使用注解中的header
            builder.removeHeader(REPLACE_HEADS);
        }else {//在注解中的header后添加配置的head
            if (this.headers != null && this.headers.size() > 0) {
                Set<String> keys = this.headers.keySet();
                for (String headerKey : keys) {
                    builder.addHeader(headerKey, this.headers.get(headerKey)).build();
                }
            }
        }

        //请求信息
        return chain.proceed(builder.build());
    }
}